﻿using System;
using System.Linq;
using WeatheRx.Data;
using WeatheRx.DomainModel.Applicants;

namespace WeatheRx.Managers.Utilities
{
    public static class StatusUtilities
    {
        private static bool IsComplete(this DateTime d)
        {
            return (d > new DateTime(1993, 1, 1));
        }

        private static bool IsComplete(this DateTime? d)
        {
            return d != null && d.GetValueOrDefault().IsComplete();
        }

        public static JobActivity DetermineNextActivity(Applicant a)
        {
            return JobActivity.Electrical;
        }

        public static JobStatus DetermineCurrentStatus(Applicant a)
        {
            if ((a.Job != null &&
                 (a.Job.Units != null &&
                  a.Job.Units.Any(x => x.Reworks != null && x.Reworks.Any(y => !y.CompletionDate.IsComplete()))) &&
                 a.Job.Units.All(
                     x => x.CloseDate.IsComplete() || x.Walkaway.GetValueOrDefault() || x.Deferral.GetValueOrDefault())))
            { return JobStatus.Completed; }

            if (a.Job != null && (a.Job.Units != null && (a.Job.Units.All(x => x.Walkaway.GetValueOrDefault())))) return JobStatus.Walkaway;
            if (a.Job != null && (a.Job.Units != null && (a.Job.Units.All(x => x.Deferral.GetValueOrDefault())))) return JobStatus.Deferral;

            //todo Add inspection dates to inspection table

            if (a.Job != null && (a.Job.Units != null && (a.Job != null && (a.Job.Units.Any(x => !x.InspectDate.IsComplete()))))) return JobStatus.InitialInspection;

            if (!a.EligibilityDate.IsComplete())
            { return JobStatus.PendingDocumentation; }
            if (a.Job == null && (a.EligibilityStatus.Equals("Ineligible") || a.LastName.Equals("Ineligible")))
            { return JobStatus.Ineligible; }
            if (a.Job != null && a.Job.WorkOrders.Any(x => !x.InvoiceDate.IsComplete())) return JobStatus.WorkInProgress;
            return JobStatus.Unspecified;
        }
    }
}